<template>
	<view class="page" v-if="user">
		<uni-header show-back title="充值" color="#F7F7F7"></uni-header>
		<view class="main-body">
			<view class="wallet-box">
					<view class="box-title">当前余额</view>
					<view class="amount iconfont icon-box" v-if="user.wallet > 10000">{{user.wallet/10000 | scale(2)}} <text class="amount-unit">w Tokens</text></view>
					<view class="amount iconfont icon-box" v-else>{{user.wallet}}<text class="amount-unit"> Tokens</text></view>
					<view class="btn btn-order"  @click="order">订单明细</view>
				</view>
				
				<view class="module">
					<view class="module-title">充值方式</view>
					<view class="module-body">
						<view class="select-option" v-for="(option, idx) in methodOptions" :class="{'active': selectedChannel == option.id}" :key="idx" @click="onMethodSelect(option)">
							<view class="option-icon iconfont" :class="'icon-' + option.id"></view>
							<view class="option-label">{{option.label}}</view>
							<view class="iconfont btn-checkbox" :class="{'icon-uncheck': selectedChannel != option.id, 'icon-checked': selectedChannel == option.id}"></view>
						</view>
					</view>
				</view>
				<view class="module">
					<view class="module-title">充值金额</view>
					<view class="module-body amount-select">
						<view class="amount-select-option" v-for="(option, idx) in amountOptions" :class="{'active': selectedAmount == option.amount}" :key="idx" @click="onAmountSelect(option)">
							<view class="option-label">{{option.amount}}元</view>
						</view>
					</view>
				</view>
				<view class="custom-amount-box">
					<view class="symbol">￥</view><input type="number" class="custom-amount" v-model="customAmount" placeholder="最低充值金额为1元" placeholder-class="input-placeholder" />
				</view>
				<view class="btn-box">
					<button class="btn-submit btn-primary" :disabled="(!customAmount && !selectedAmount) || submitting" @click="submit">立即充值</button>
				</view>
			</view>
			
		</view>
		<uni-loading v-else></uni-loading>
</template>
<script>
	import Storage from '@/mpf/cache/storage'
	const isWexin = navigator && navigator.userAgent && navigator.userAgent.toLowerCase().indexOf('micromessenger') > -1;
	//const methodOptions = [{id:'alipay', label:'支付宝'}, {id: 'wxpay', label: '微信支付'}];
	const methodOptions = isWexin ?  [{id: 'wxpay', label: '微信支付'}] : [{id:'alipay', label:'支付宝'}];
	const OPEN_ID_CACHE = "WEIXIN_OPEN_ID";
	export default {
		data() {
			return {
				user: null,
				methodOptions: methodOptions,
				amountOptions:[],
				selectedChannel: methodOptions[0].id,
				selectedAmount: null,
				customAmount: null,
				submitting: false,
				interval: null,
				openId: null
			}
		},
		onLoad(options) {
			if(isWexin){
				let code = options.code;
				if(code){
					this.$api.wechatService.openid(code).then(res => {
						this.openId = res.value;
						Storage.set(OPEN_ID_CACHE, this.openId);
						uni.redirectTo({
							url:'/pages/common/recharge'
						})
					});
				}
				else{
					this.openId = Storage.get(OPEN_ID_CACHE);
					this.loadWechatConfig();
				}
				
			}
			
		},
		
		onShow() {
			
			this.loadData();
		},
		onUnload() {
			this.clearInterval()
		},
		watch:{
			customAmount(newVal, oldVal){
				if(newVal){
					this.selectedAmount = null;
				}
			}
		},
		methods: {
			loadWechatConfig(){
				this.$api.wechatService.config(location.href).then(res => {
					if(!this.openId){
						let redirectUrl = encodeURIComponent(location.href)
						location.replace(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${res.app_id}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_base&state=recharge#wechat_redirect`)
					}	
				});
			},
			clearInterval(){
				if(this.interval){
					clearInterval(this.interval);
					this.interval = null;
				}
			},
			loadData(){
				this.$api.userService.info().then(res => {
					this.user = res;
				})
				
				this.$api.rechargeAmountService.findList().then(res => {
					
					this.amountOptions = res.items;
	
					if(this.amountOptions.length > 0){
						this.selectedAmount = this.amountOptions[0].amount;
					}
					
				});
			},
			/**
			 * 订单详情
			 */
			order(){
				uni.navigateTo({
					url:"/pages/common/order"
				})
			},
			/**
			 * 选择支付方式
			 * @param {Object} item
			 */
			onMethodSelect(item){
				this.selectedChannel = item.id;
			},
			/**
			 * 选择金额
			 * @param {Object} item
			 */
			onAmountSelect(item){
				this.customAmount = null;
				this.selectedAmount = item.amount;
			},
			/**
			 * 提交充值
			 */
			submit(){
				if(this.submitting){
					return ;
				}
				let amount = this.customAmount || this.selectedAmount;
				if(!amount){
					global.error('请设置要充值的金额');
					return ;
				}
				
				if(amount < 1 && amount != this.selectedAmount){
					global.error("最低充值金额为1元");
					return ;
				}
				if(!/[1-9]\d*/.test(amount)){
					global.error('请填写整数金额');
					return ;
				}
				
				let redirectUrl = '';
				if(location){
					var pages = getCurrentPages();
					var len = pages.length;
					let path = ''
					if (len > 1) {
					  var prevPage = pages[len - 2];
					  console.log(prevPage);
					  path = '/' + prevPage.route;
					}
					
					redirectUrl = location.protocol + '//' + location.host  + path;
				}
				
				this.submitting = true;
				this.$api.payService.recharge({
					redirect_url:redirectUrl, 
					amount: amount,
					pay_channel:this.selectedChannel,
					open_id: this.openId
				}).then(res => {
					if(res.value){
						if(isWexin){
							let payInfo = JSON.parse(res.value);
							window.WeixinJSBridge.invoke(
							'getBrandWCPayRequest', {
								"appId": payInfo.appId, //公众号名称，由商户传入     
								"timeStamp": payInfo.timeStamp, //时间戳，自1970年以来的秒数     
								"nonceStr": payInfo.nonceStr, //随机串     
								"package": payInfo.package,
								"signType": payInfo.signType, //微信签名方式：     
								"paySign": payInfo.paySign //微信签名 
							}, (res) => {
								if (res.err_msg == "get_brand_wcpay_request:ok") {
									console.log(value)
								} else {
									global.toast('支付失败');
								}
							});
						}
						else if(location){
							location.href = res.value
						};
						this.interval = setInterval(() => {
							this.$api.payService.query(res.order_id).then(res => {
								if(res.success){
									uni.navigateBack()
								}
							});
						}, 1000);
					}
				}).finally(() => {
					console.log('finally')
					setTimeout(() => {
						this.submitting = false;
					}, 300)
					
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page{
		display: flex;
		flex-direction: column;
	}
	.main-body{
		flex:1;
		overflow-y: auto;
	}
	.wallet-box{
		width: 666rpx;
		height: 254rpx;
		background: #86DFBA;
		border-radius: 20rpx;
		margin:40rpx auto 0;
		color: #FFFFFF;
		padding:48rpx 40rpx;
		box-sizing: border-box;
		position: relative;
		
		.box-title{
			font-size: 30rpx;
			line-height: 42rpx;
		}
		.amount{
			margin-top: 40rpx;
			font-size: 56rpx;
			.amount-unit{
				font-size: 40rpx;
				margin-left: 10rpx;
			}
		}
		
		.btn-order{
			position: absolute;
			right: 0;
			
			height: 90rpx;
			line-height: 90rpx;
			padding: 0 34rpx;
			border-radius: 45rpx 0 0 45rpx;
			top:50%;
			margin-top:-45rpx;
			font-size: 30rpx;
			color:#677A3F;
			background: rgba(255,255,255,0.3);
		}
	}
	
	.module{
		color:#FFFFFF;
		box-sizing: border-box;
		padding:40rpx 30rpx;
		margin:0 auto;
		width: 730rpx;
		.module-title{
			line-height: 40rpx;
			font-size: 28rpx;
			margin-bottom: 40rpx;
		}
		
		.module-body{
			.select-option{
				display: flex;
				align-items: center;
				margin-bottom:66rpx;
				
				&:last-child{
					margin-bottom: 0rpx;
				}
				
				.option-icon{
					font-size: 40rpx;
					background: #FFFFFF;
					border-radius: 8rpx;
					margin-right:18rpx;
					
					&.icon-alipay{
						color:#02A9F1;
					}
					&.icon-wxpay{
						color:#40BA49;
					}
				}
				.option-label{
					flex:1;
					line-height: 40rpx;
					font-size:32rpx;
					
				}
				
				.btn-checkbox{
					font-size: 36rpx;

				}
				
				
				&.active{
					.btn-checkbox{
						color:$uni-color-primary;
					}
				}
				
				
			}
		}
		
		
	}
	.amount-select{
		display: flex;
		flex-wrap: wrap;
		width: 664rpx;
		.amount-select-option{
			width: 208rpx;
			height: 108rpx;
			background: rgba(255,255,255,0.05);
			border-radius: 20rpx;
			line-height: 106rpx;
			text-align: center;
			font-size: 30rpx;
			box-sizing: border-box;
			margin-right: 20rpx;
			margin-bottom: 20rpx;
			border: 1rpx solid rgba(255,255,255,0.05);
			
			&:nth-child(3n){
				margin-right: 0;
			}
			
			
			&.active{
				color:$uni-color-primary;
				border: 1rpx solid $uni-color-primary;
				
			}
		}
	}
	
	.custom-amount-box{
		width: 670rpx;
		margin: 30rpx auto 0;
		display: flex;
		border-bottom: 1rpx solid rgba(234,234,234,0.1);
		color: #F7F7F7;
		padding-bottom: 20rpx;
		line-height: 44rpx;
		align-items: center;
		font-size: 32rpx;
		.custom-amount{
			height: 44rpx;
			flex:1;
			font-size: 32rpx;
			font-weight: 400;
			padding-left:12rpx;
		}
		
		.input-placeholder{
			color:#E0E0E0;
			font-size: 32rpx;
			line-height: 44rpx;
		}
	}
	
	.btn-box{
		background-color: transparent!important;
		margin-top:130rpx;
		padding-bottom: 40rpx;
		.btn-submit{
			width: 590rpx;
			height: 108rpx;
			line-height: 108rpx;
			border-radius: 20rpx;
			padding:0;
			margin:0 auto;
			font-size: 32rpx;
			font-weight: bold;
			letter-spacing: 3rpx;
		}
	}
	
	
</style>
